package com.wolfking.jeesite.util;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.StreamSupport;

public class EnvironmentUtil {

    public static Map<String, String> getEnvironment(ConfigurableEnvironment environment, String prefix) {
        Map<String, String> props = Maps.newHashMap();
        MutablePropertySources propSrcs = environment.getPropertySources();
        StreamSupport.stream(propSrcs.spliterator(), false)
                .filter(ps -> ps instanceof EnumerablePropertySource)
                .map(ps -> ((EnumerablePropertySource<?>) ps).getPropertyNames())
                .flatMap(Arrays::stream)
                .filter(k -> k.startsWith(prefix))
                .forEach(propName -> {
                    String property = environment.getProperty(propName);
                    if (StringUtils.isNotBlank(propName)) {
                        props.put(propName.substring(prefix.length()), property);
                    }
                });
        return props;
    }
}
